package com.huike.springboot1.demos.service.impl;

import com.huike.springboot1.demos.Mapper.User1Mapper;
import com.huike.springboot1.demos.pojo.User1;
import com.huike.springboot1.demos.service.User1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class User1ServiceImpl implements User1Service {

    @Autowired
    private User1Mapper user1Mapper;
    @Autowired
    private PasswordEncoder passwordEncoder;//加密器

    @Override
    public User1 findByUsername(String username) {
        return user1Mapper.selectByUsername(username);
    }

    @Override
    public User1 findUserWithRoles(Long userId) {
        return user1Mapper.selectUserRoles(userId);
    }

    @Override
    public User1 findById(Long id) {
        return user1Mapper.selectById(id);
    }

//    开启事务
    @Transactional // 事务保证：用户和角色关联同时成功
    @Override
    public void add(User1 user1, List<Long> roleIds) {
        // 密码加密（默认密码123456）
//        user1.setPassword(passwordEncoder.encode("123456"));
//        自主获取加密密码
//        user1.setPassword(passwordEncoder.encode(user1.getPassword()));

//        user1.setPassword("123456"); // 设置管理员端的默认密码
        user1.setPassword(user1.getPassword());
        user1.setStatus(1); // 默认启用
        user1Mapper.insert(user1);
        // 关联角色
        if (roleIds != null && !roleIds.isEmpty()) {
            user1Mapper.batchInsertUserRoles(user1.getId(), roleIds);
        }
    }

    @Transactional
    @Override
    public void update(User1 user1, List<Long> roleIds) {
        // 更新用户基本信息（不更新密码）
        user1Mapper.update(user1);
        // 先删后加：更新角色关联
        user1Mapper.deleteUserRoles(user1.getId());
        if (roleIds != null && !roleIds.isEmpty()) {
            user1Mapper.batchInsertUserRoles(user1.getId(), roleIds);
        }
    }

    @Transactional
    @Override
    public void delete(Long id) {
        // 先删角色关联，再删用户
        user1Mapper.deleteUserRoles(id);
        user1Mapper.delete(id);
    }

//    邮箱验证码
    @Override
    public boolean existsByEmail(String email) {
        return user1Mapper.countByEmail(email) > 0;
    }
}
